package com.rlyy.basic.resolver.exception;

import org.springframework.util.Assert;

import java.util.Comparator;

/**
 * 获取最适合的异常处理类
 *
 * @author yuanqinglong
 * @since 2020/11/30 9:34
 */
public class MyExceptionDepthComparator implements Comparator<Class<? extends Throwable>> {

    /**
     * 实际抛出的异常
     */
    private final Class<? extends Throwable> targetException;

    public MyExceptionDepthComparator(Class<? extends Throwable> exceptionType) {
        Assert.notNull(exceptionType, "抛出的异常类型为空");
        this.targetException = exceptionType;
    }

    @Override
    public int compare(Class<? extends Throwable> o1, Class<? extends Throwable> o2) {
        int depth1 = getDepth(o1, this.targetException, 0);
        int depth2 = getDepth(o2, this.targetException, 0);
        return (depth1 - depth2);
    }

    /**
     * 获取离抛出的异常深度最近的处理类
     */
    private int getDepth(Class<?> declaredException, Class<?> exceptionToMatch, int depth) {
        if (exceptionToMatch.equals(declaredException)) {
            return depth;
        }
        // 如果抛出的异常返回时Throwable排在最后
        if (exceptionToMatch == Throwable.class) {
            return Integer.MAX_VALUE;
        }
        return this.getDepth(declaredException, exceptionToMatch.getSuperclass(), depth + 1);
    }
}
